package com.yoga.manager.upyun;

import com.yoga.common.appexception.AppErrorCodeEnum;
import com.yoga.common.appexception.AppException;
import com.yoga.common.appexception.YogaResult;
import com.yoga.manager.uitl.DateUtil;
import main.java.com.UpYun;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Random;

/**
 * 文件上传
 */
public class UploadUtils {
    private static String folder = System.getProperty("java.io.tmpdir");

    private static Logger logger = LoggerFactory.getLogger(UploadUtils.class);

    private static String DOME="http://image-czt.test.upcdn.net";

    // 间隔标识符 用于分隔文件 URL 和文件参数
    private static final String SEPARATOR = "!";

    private static final String SLASH = "/";

    private static final Random R = new Random();

    // 声明并初始化友护云工具类
    private static UpYun cztupyun;

    private static UpYun upyun=null;

    static {
        cztupyun = new UpYun(Config.instance().bucket, Config.instance().username, Config.instance().password);
    }




        /**
         * 图片上传
         *
         * @param file     文件对象
         * @param isSecret 是否设置访问秘钥 是：true
         */
    public static String imageUpload(UploadChannelEnum uploadChannelEnum, File file, Boolean isSecret) throws IOException {
        if (file == null) {

            return "";
        }
        upyun=cztupyun;
        try {
            Boolean flag=false;
            String path = getFilePath(uploadChannelEnum, file.getName(), "img");
            upyun.setContentMD5(UpYun.md5(file));
            if (isSecret) {
                upyun.setFileSecret(Config.instance().FILE_SECRET);
            }
            flag = upyun.writeFile(path, file, true);
            if (flag) {

                if (isSecret) {
                    return path + SEPARATOR + Config.instance().FILE_SECRET;
                }
                return DOME+path;
            }

        }finally {
            //删除临时图片！
            if(file.exists()){
               file.delete();
            }
        }
        return "";
    }

    /**
     * 文件上传
     *
     * @param file     文件对象
     * @param isSecret 是否设置访问秘钥 是：true
     */
    public static String fileUpload(UploadChannelEnum uploadChannelEnum,File file, Boolean isSecret, String type) throws IOException {

        if (file == null) {
            return "";
        }
        upyun=cztupyun;

        String path = getFilePath(uploadChannelEnum,file.getName(), type);

        upyun.setContentMD5(UpYun.md5(file));

        if (isSecret) {
            upyun.setFileSecret(Config.instance().FILE_SECRET);
        }

        Boolean flag = upyun.writeFile(path, file, true);

        if (flag) {
            if (isSecret) {
                return DOME+path + SEPARATOR + Config.instance().FILE_SECRET;
            }
            return DOME+path;
        }
        return "";
    }

    /**
     * 图片上传
     *
     * @param file     文件对象
     * @param isSecret 是否设置访问秘钥 是：true
     */
    public static String imageUpload(UploadChannelEnum uploadChannelEnum,String fileName, byte[] file, Boolean isSecret) throws IOException {

        if (fileName == null) {

            return "";
        }

        String path = getFilePath(uploadChannelEnum,fileName, "img");

        //upyun.setContentMD5(UpYun.md5(file));

        upyun=cztupyun;

        if (isSecret) {

            upyun.setFileSecret(Config.instance().FILE_SECRET);
        }
        Boolean flag = upyun.writeFile(path, file, true);

        if (flag) {

            if (isSecret) {

                return DOME+path + SEPARATOR + Config.instance().FILE_SECRET;
            }
            return DOME+path;
        }

        return "";
    }

    /**
     * 文件存储位置及文件名称生成规则
     *
     * @param fileName 文件的名称
     * @param type     上传文件的类型，图片:"img"，其他暂无
     * @return
     * @author ShenQuan
     */
    private static String getFilePath(UploadChannelEnum uploadChannelEnum,String fileName, String type) {

        if (StringUtils.isBlank(fileName)) {

            return "";
        }
        StringBuilder path = new StringBuilder();

        boolean  isImgUpload = "img".equals(type)||"json".equals(type)||"file".equals(type);
        if(isImgUpload){
            conbination(uploadChannelEnum,path, fileName, type);
        }else {
            // 非图片文件使用原始名称
            path.append(Config.instance().FILE_DIR).append("/").append(fileName);
        }


        return path.toString();
    }

    /**
     * https://laquimage.b0.upaiyun.com/invite_qrcode/2019/3/21/img1553182701118_631.png
     * @param uploadEnum
     * @param path
     * @param fileName
     * @param type
     */
    private static void conbination(UploadChannelEnum uploadEnum,StringBuilder path, String fileName, String type) {
        path.append(SLASH).append(uploadEnum.name().toLowerCase()).append(SLASH);
        // 图片所属的文件夹  追加上年月日
        Date now=new Date();
        path.append(DateUtil.getYear(now)).append(SLASH).append(DateUtil.getMonth(now)).append(SLASH).append(DateUtil.getDate(now))
                // 文件名称生成规则 img+时间戳+三位随机数+文件后缀
                .append(SLASH).append(type).append(System.currentTimeMillis());
        path.append("_");
        path.append(R.nextInt(10)).append(R.nextInt(10)).append(R.nextInt(10));
        int index = fileName.indexOf(".");
        if (index > -1) {
            String suffix = StringUtils.substring(fileName, index);
            path.append(suffix);
        }
    }

    public static byte[] File2byte(String filePath) throws IOException {
        byte[] buffer = null;
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        buffer = bos.toByteArray();
        return buffer;
    }


    public static YogaResult upload(UploadChannelEnum uploadChannel, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffix = fileName;
        if (StringUtils.isNotBlank(fileName)) {
            if (fileName.contains(".")){
                suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            }
        }
        if(uploadChannel == null){
            throw new AppException(AppErrorCodeEnum.PARAMETER_NULL);
        }
        Path path = Paths.get(folder, System.currentTimeMillis() + suffix);

        YogaResult appResult =null;

        try {
            Files.copy(file.getInputStream(), path);
            File imgFile = path.toFile();
            String imgUrl = UploadUtils.imageUpload(uploadChannel,imgFile, false);
            appResult=new YogaResult(imgUrl);
            imgFile.delete();
        } catch (IOException e) {
            logger.error("上传图片出错!", e);
            return YogaResult.badArgumentValue();
        }
        return appResult;
    }

    public static void main(String[] args) throws IOException, AppException {

        try {

            String file="/Users/chenjin/Desktop/图片/1.jpeg";

            String path= UploadUtils.imageUpload(UploadChannelEnum.YOGA_IMG,new File(file),false);

            System.out.println(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

